//
//  ShopEditViewController.m
//  BabyAndBaby
//
//  Created by 范琦 on 16/8/1.
//  Copyright © 2016年 范琦. All rights reserved.
//

#import "ShopEditViewController.h"
#import "LyScrollMenu.h"
#import "ShopMenuModel.h"
#import "ShopDetailCell.h"
#import "getDistrictModel.h"
#import "recommendTopView.h"

@interface ShopEditViewController ()<UIWebViewDelegate, UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, strong) NSMutableArray *listArr;
@property (nonatomic, strong) LyScrollMenu *scroll;
@property (nonatomic, strong) NSMutableArray *viewArr;      //滚动view数组
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *pqArr;      //片区数组
@property (nonatomic, strong) UIPickerView *pickView;
@property (nonatomic, strong) UIView *pickTopView;
@property (nonatomic, strong) recommendTopView *recommendTop;
@property (nonatomic, strong) NSString *pqStr;      //片区数组
@property (nonatomic, strong) NSString *pqIdStr;      //片区数组

@end

@implementation ShopEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"商户编辑";
    _viewArr = [NSMutableArray array];
    self.pqArr = [NSMutableArray array];

    self.listArr = [NSMutableArray arrayWithObjects:@"商户编号:",@"商户名称:",@"联系人:",@"登陆账号(手机号):",@"详细地址:",@"店主姓名:",@"店主电话:", nil];
    [self creatTableView];
    [self creatView];
    [self creatMenuScroll];
    [self getData];
}
#warning 片区信息请求
- (void)getData
{
    if (_pqArr.count == 0) {
        
        YTKNetHandle *api = [[YTKNetHandle alloc] initWithUrl:[NSString stringWithFormat:@"/Merchant/getMerchantArea.html?token=%@",TOKEN] RegisterApiMethod:RequestMethodGet];
        [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            NSArray *arr = [request.responseBody objectForKey:@"result"];
            NSLog(@"%@", arr);
            for (NSDictionary *dic in arr) {
                getDistrictModel *model = [[getDistrictModel alloc] init];
                model.area_id = [dic objectForKey:@"area_id"];
                model.name = [dic objectForKey:@"name"];
                [self.pqArr addObject:model];
            }
            getDistrictModel *model =_pqArr[0];
            _pqStr = model.name;
            _pqIdStr = [NSString stringWithFormat:@"%@", model.area_id];
            [_pickView reloadAllComponents];
        } failure:^(YTKBaseRequest *request) {
            
        }];
    }
}
#warning 创建PickerView
- (void)creatPickerView:(UIButton *)btn
{
    if (_pickView == nil) {
        
        self.pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, KSCREENHEIGHT - 150, KSCREENWIDTH, 150)];
        _pickView.frame = CGRectMake(0, KSCREENHEIGHT - 144, KSCREENWIDTH, 144);
        _pickView.delegate = self;
        _pickView.dataSource = self;
        [self.view addSubview:_pickView];
        _pickView.backgroundColor = [UIColor huiseColor];
        
        self.pickTopView = [[UIView alloc]initWithFrame:CGRectMake(0, _pickView.frame.origin.y - 30, KSCREENWIDTH, 30)];
        [self.view addSubview:_pickTopView];
        _pickTopView.backgroundColor = HUIBACKGROUNDCOLOR;
        
    }else{
        [self.view addSubview:_pickView];
        [self.view addSubview:_pickTopView];
    }
    UIButton *done = [UIButton buttonWithType:UIButtonTypeSystem];
    [done setTitle:@"Done" forState:UIControlStateNormal];
    done.frame = CGRectMake(KSCREENWIDTH - 60, 0, 40, 30);
    done.tintColor = [UIColor blackColor];
    [_pickTopView addSubview:done];
    [[done rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [_pickView removeFromSuperview];
        [_pickTopView removeFromSuperview];
        
        _recommendTop.districtLabel.text = _pqStr;
    }];
    
}
- (void)netHandle
{
    YTKNetHandle *api = [[YTKNetHandle alloc] initWithUrl:@"/Merchant/merchantSave.html" paramDic:@{
                                                        @"token":TOKEN ,
                                                        @"id":_str,
                                                        @"area_id":_pqIdStr,
                                                        @"number":_listArrDetail[0],
                                                        @"name_merchant":_listArrDetail[1],
                                                        @"user_name":_listArrDetail[3],
                                                        @"contact_name":_listArrDetail[2],
                                                        @"address":_listArrDetail[4],
                                                        @"name":_listArrDetail[5],
                                                        @"boss_phone":_listArrDetail[6],
                                                        
                                                                         } RegisterApiMethod:RequestMethodPost];
    [api startWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        
        NSLog(@"%@", request.responseBody[@"error"]);
        if ([request.responseBody[@"error"] integerValue] == 0) {
            
            NSLog(@"%@", request.responseBody[@"result"]);
            [self showAlertView:request.responseBody[@"result"] timeOut:1];
            [self.navigationController popViewControllerAnimated:YES];
        }
        
    } failure:^(YTKBaseRequest *request) {
        
    }];
}
#warning 创建所有View
- (void)creatView
{
    for (int i = 0; i < _menuArr.count; i++) {
        UIWebView *view = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, _scroll.bounds.size.height)];
        ShopMenuModel *model = _menuArr[i];
        NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@?uid=%@",model.url,_str]];
        NSURLRequest *request =[NSURLRequest requestWithURL:url];
        [view loadRequest:request];
        [_scroll addSubview:view];
        view.delegate = self;
        [self.viewArr addObject:view];
    }
}

- (void)creatMenuScroll
{
    self.scroll = [[LyScrollMenu alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, KSCREENHEIGHT) ControllerViewArray:_viewArr TitleArray:_menuStrArr MaxShowTitleNum:5];
    
    
    [self.view addSubview:_scroll];
}
- (void)creatTableView
{
    
    UIView *oneView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, _scroll.bounds.size.height)];
    self.recommendTop = [[[NSBundle mainBundle] loadNibNamed:@"recommendTopView" owner:nil options:nil] lastObject];
    //    _recommendTop.backgroundColor = [UIColor redColor];
    _recommendTop.frame = CGRectMake(0, 10, KSCREENWIDTH, 33 * KSCREENHEIGHT / 667);
    [[_recommendTop.bigButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self getData];
        [self creatPickerView:_recommendTop.bigButton];
    }];
//    [oneView addSubview:_recommendTop];
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0,0, KSCREENWIDTH, KSCREENHEIGHT - 44 - 44 - self.navigationController.navigationBar.frame.size.height - 20) style:UITableViewStyleGrouped];
    [oneView addSubview:_tableView];
    _tableView.tableHeaderView = _recommendTop;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.backgroundColor = HUIBACKGROUNDCOLOR;
    [_tableView registerNib:[UINib nibWithNibName:@"ShopDetailCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    _tableView.sectionFooterHeight = 0;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.showsVerticalScrollIndicator = NO;
    
    
    UIButton *editBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    editBtn.frame = CGRectMake(0, _tableView.bounds.size.height, KSCREENWIDTH, 44);
    [editBtn setTitle:@"保存" forState:UIControlStateNormal];
    editBtn.tintColor = [UIColor whiteColor];
    editBtn.backgroundColor = BACKGROUNDCOLOR;
    [[editBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self netHandle];
    }];
    [oneView addSubview:editBtn];
    [_scroll addSubview:oneView];
    [_viewArr addObject:oneView];
}
#warning tableView代理方法
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 43;
    }
    return 58;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 5;
    }
    return 2;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 15 + 33;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KSCREENWIDTH, 33 + 15)];
    view.backgroundColor = HUIBACKGROUNDCOLOR;
    UIView *back = [[UIView alloc]initWithFrame:CGRectMake(0, 15, KSCREENWIDTH, 33)];
    back.backgroundColor = [UIColor whiteColor];
    [view addSubview:back];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 12, KSCREENWIDTH, 21)];
    label.backgroundColor = [UIColor whiteColor];
    if (section == 0) {
        label.text = @"基本信息";
    }else
    {
        label.text = @"验证信息";
    }
    label.textColor = [UIColor colorWithRed:76 / 255.0 green:217 / 255.0 blue:192 / 255.0 alpha:1];
    label.font = [UIFont systemFontOfSize:16];
    [back addSubview:label];
    return view;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ShopDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (indexPath.section == 0 && _listArrDetail.count != 0) {
        cell.textField.text = [NSString stringWithFormat:@"%@ %@", _listArr[indexPath.row], _listArrDetail[indexPath.row]];

        [[cell.textField rac_signalForControlEvents:UIControlEventEditingDidEnd] subscribeNext:^(id x) {
            NSString *str = cell.textField.text;
            [_listArrDetail replaceObjectAtIndex:indexPath.row withObject:str];
            cell.textField.text = [NSString stringWithFormat:@"%@ %@", _listArr[indexPath.row], str];

        }];
    }else if (indexPath.section == 1 && _listArrDetail.count != 0){
        cell.textField.text = [NSString stringWithFormat:@"%@ %@", _listArr[indexPath.row + 5], _listArrDetail[indexPath.row + 5]];
        [[cell.textField rac_signalForControlEvents:UIControlEventEditingDidEnd] subscribeNext:^(id x) {
            NSString *str = cell.textField.text;
            [_listArrDetail replaceObjectAtIndex:indexPath.row + 5 withObject:str];
            cell.textField.text = [NSString stringWithFormat:@"%@ %@", _listArr[indexPath.row + 5], str];
            
        }];
    }
    
    [[cell.textField rac_signalForControlEvents:UIControlEventEditingDidBegin] subscribeNext:^(id x) {
        NSArray *arr = [cell.textField.text componentsSeparatedByString:@":"];
        cell.textField.text = [arr lastObject];
    }];
    return cell;
}
#warning PickerView代理方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    
    return _pqArr.count;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    getDistrictModel *model =_pqArr[row];
    _pqIdStr = model.name;
    return model.name;
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    getDistrictModel *model =_pqArr[row];
    _pqStr = model.name;
    _pqIdStr = [NSString stringWithFormat:@"%@", model.area_id];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
